package com.cpd.blog.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cpd.blog.manager.mapper.ArticleMapper;
import com.cpd.blog.entity.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author Copydown
 * @date 2021/8/17 20:49
 */
@Component
public class ThreadService {

    /**
     * 期望此操作在线程池执行，不影响主线程操作
     */
    @Async("myThreadPool")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {

        Long viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();

        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());

        //为了多线程下的线程安全
        updateWrapper.eq(Article::getViewCounts, viewCounts);

        articleMapper.update(articleUpdate, updateWrapper);
    }
}
